package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.result.UserInfo;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;


/**
 * @author tan
 * @date 2023年01月10日 11:00
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverter;

    @Override
    public ResponseData login(UserLoginRequest request) {
        //校验参数是否合法
        if (StringUtils.isEmpty(request.getUserName()) || StringUtils.isEmpty(request.getUserPwd())) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        }
        //从数据库校验密码
        Member member = new Member();
        member.setUsername(request.getUserName());
        member = memberMapper.selectOne(member);

        String realPWD = new AESUtil(member.getPassword()).decrypt();
        if (!request.getUserPwd().equals(realPWD)) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }
        //是否验证
        if (!member.getIsVerified().equals("Y")) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }
        //获取信息
        UserLoginResponse userLoginResponse = userConverter.converter(member);
        //设置token
        UserInfo userInfo = new UserInfo(userLoginResponse.getId(), userLoginResponse.getUsername());
        String s = JSON.toJSONString(userInfo);
        String token = JwtTokenUtils.builder().msg(s).build().creatJwtToken();
        userLoginResponse.setToken(token);
        return new ResponseUtil<>().setData(userLoginResponse);
    }

    @Override
    public String getMemberFile(Long uid) {
        Member member = memberMapper.selectByPrimaryKey(uid);
        return member.getFile();
    }
}

